package me.dwliu.ebase.modules.gen.exception;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import me.dwliu.ebase.modules.gen.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 异常处理器
 *
 * @author liudw
 * @date 2020/8/23 20:17
 **/
@Component
@Slf4j
public class CustomExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
        log.error(ex.getMessage(), ex);
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        Result result = new Result();
        if (ex instanceof CustomException) {
            result.put("code", ((CustomException) ex).getCode());
            result.put("msg", ex.getMessage());
        } else {
            result = Result.error();
        }

        try {
            response.getWriter().print(JSON.toJSONString(result));
        } catch (IOException e) {
            //丢弃
        }

        return new ModelAndView();
    }
}
